import { Component, OnInit } from '@angular/core';
import {
  NavigationCancel,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  RouteConfigLoadEnd,
  RouteConfigLoadStart,
  Router
} from '@angular/router';
import { takeUntil, timer } from 'rxjs';

import { DestroyService } from '@core/base';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-base-router-progress-bar',
  templateUrl: './router-progress-bar.component.html',
  styleUrls: ['./router-progress-bar.component.less'],
  providers: [DestroyService]
})
export class RouterProgressBarComponent implements OnInit {
  isFetching = false;

  constructor(private router: Router, private destroy$: DestroyService, private messageSrc: NzMessageService) {}

  ngOnInit(): void {
    this.router.events.pipe(takeUntil(this.destroy$)).subscribe(evt => {
      // 表示在惰性加载某个路由配置前触发的事件。
      if (!this.isFetching && evt instanceof RouteConfigLoadStart) {
        this.isFetching = true;
      }
      if (!this.isFetching && evt instanceof NavigationStart) {
        this.isFetching = true;
      }
      if (evt instanceof NavigationError || evt instanceof NavigationCancel) {
        this.isFetching = false;
        if (evt instanceof NavigationError) {
          this.messageSrc.error(`无法加载路由： ${evt.url}`, { nzDuration: 1000 * 3 });
        }
        return;
      }
      if (!(evt instanceof NavigationEnd || evt instanceof RouteConfigLoadEnd)) {
        return;
      }
      if (this.isFetching) {
        timer(100).subscribe(() => {
          this.isFetching = false;
        });
      }
    });
  }
}
